<template>
  <div class="content">
    <div class="cloud-header">
      <h2>表格管理</h2>
    </div>
    <div class="cloud-layout cloud-fixation cloud-tables">
      <Layout>
        <Sider>
          <div class="cloud-menus">
            <Menu :datas="menuData" :accordion="true" ref="menu" className="h-menu-white" @select="handleSelect"></Menu>
            <div class="cloud-menus-tools">
              <div class="h-btn-group h-btn-group-s">
                <button class="h-btn" v-popup.newTable><i class="h-icon-plus"></i><span>新建</span></button>
                <button class="h-btn"><i class="h-icon-outbox"></i><span>导出</span></button>
                <button class="h-btn"><i class="h-icon-inbox"></i><span>导入</span></button>
              </div>
            </div>
          </div>
        </Sider>
        <Layout>
          <HHeader>
            <div class="cloud-tools">
              <ButtonGroup  v-if="JSON.stringify(tableData) !== '{}'">
                <Button icon="h-icon-plus" @click="handleAddField">添加</Button>
                <Button icon="h-icon-check" @click="handleSaveField">保存</Button>
                <Button icon="h-icon-trash" @click="handleDeleteField">删除</Button>
                <Button icon="h-icon-refresh">刷新</Button>
                <Button icon="h-icon-outbox">导出</Button>
              </ButtonGroup>
            </div>
          </HHeader>
          <Content ref="content">
            <Table :datas="fields" :selectRow="true" :height="height" selectWhenClickTr @trclick="handleSelectField">
              <TableItem title="名" :width="200">
                <template slot-scope="{data}">
                  <input class="cloud-input" autocomplete="off" type="text" name="name" v-model="data['name']">
                </template>
              </TableItem>
              <TableItem title="类型" :width="130" align="center" sort="auto">
                <template slot-scope="{data}">
                  <Select v-model="data['type']" :datas="typeData" :deletable="false"></Select>
                </template>
              </TableItem>
              <TableItem title="长度" :width="100">
                <template slot-scope="{data}">
                  <input class="cloud-input" autocomplete="off" type="text" name="length" v-model="data['length']" placeholder="0">
                </template>
              </TableItem>
              <TableItem title="必填" :width="60" prop="address">
                <template slot-scope="{data}">
                  <Checkbox v-model="data['required']" :trueValue="true" :falseValue="false"></Checkbox>
                </template>
              </TableItem>
              <TableItem title="备注" :width="180" prop="address">
                <template slot-scope="{data}">
                  <input class="cloud-input" autocomplete="off" type="text" name="title" v-model="data['title']">
                </template>
              </TableItem>
              <div slot="empty">自定义提醒：暂时无数据</div>
            </Table>
            <!-- <div class="clear"></div> -->
          </Content>
          <HFooter>
            <div class="cloud-footer">
              <CloudAttribute v-model="field"></CloudAttribute>
            </div>
          </HFooter>
        </Layout>
      </Layout>
    </div>
  </div>
</template>
<script type="text/javascript">
export default {
  data() {
    return {
      typeData: {
        'string': 'string',
        'array': 'array',
        'object': 'object',
        'number': 'number',
        'objectid': 'objectid',
        'boolean': 'boolean',
        'double': 'double',
        'auto_increment': 'auto_increment',
        'date': 'date'
      },
      menuData: [{
        title: '数据库表',
        icon: 'h-icon-task',
        key: 'database',
        children: []
      }],
      height: 467,
      tableData: {},
      fields: [],
      field: {},
      index: null,
      update: false
    };
  },
  /**
   * 页面加载执行
   * @return {[type]} [description]
   */
  mounted() {
    this.handleTableList();
    this.calculateheight();
  },
  /**
   * 数据监听
   * @type {Object}
   */
  watch: {
    // field: { //监听的对象
    //   deep: true, //深度监听设置为 true
    //   handler: function(newValue, oldValue) {
    //     console.log("监听动盘", newValue.title)
    //   }
    // }
  },
  methods: {
    handleUpdate(data) {
      // this.field = data;
      this.$set(this.fields, this.index, data);
    },
    /**
     * 选中字段
     * @return {[type]} [description]
     */
    handleSelectField(data, event, index) {
      this.index = index;
      this.field = data;
    },
    /**
     * 删除字段
     * @return {[type]} [description]
     */
    handleDeleteField() {
      let { index } = this;
      if (this.fields[index]) {
        this.fields.splice(index, 1);
        this.index = 0;
      }
    },
    /**
     * 添加字段
     * @return {[type]} [description]
     */
    handleAddField() {
      this.fields.push({
        name: '',
        type: 'string',
        title: '',
        length: 0,
        required: false
      });
    },
    /**
     * 保存字段
     * @return {[type]} [description]
     */
    handleSaveField() {
      let { _id, explain, auth } = this.tableData;
      // 处理字段
      let fields = {};
      // 字段处理
      for (let i in this.fields) {
        let item = this.fields[i];
        fields[item.name] = {
          title: item.title || '',
          type: item.type || 'string',
          length: item.length || 0,
          required: item.required || false,
          default: item.default || '',
          form: item.form || { hide: true, type: 'input' }
        };
      }
      this.$cloud.tables().edit(_id, {
        'explain': explain,
        'auth': auth,
        'fields': fields
      }).then(res => {
        this.$Message.success('保存成功');
      }).catch(error => {
        console.log('错误', error);
      });
    },
    /**
     * 计算高度
     * @return {[type]} [description]
     */
    calculateheight() {
      console.log(this.$refs.content.$el.offsetHeight)
      this.$nextTick(() => {
        this.height = this.$refs.content.$el.offsetHeight - 47;
      });
    },
    /**
     * 选择菜单
     * @param  {[type]} menu [description]
     * @return {[type]}      [description]
     */
    handleSelect(menu) {
      this.calculateheight();
      this.$refs.menu.select(menu.key);
      // 初始化当前字段
      this.index = 0;
      this.$cloud.tables().get({
        'AppID': this.$cloud.AppID,
        'name': menu.key
      }).then(res => {
        this.tableData = res;
        let fields = [];
        if (res && res.fields) {
          for (let key in res.fields) {
            let item = res.fields[key];
            if (key == '_userid' || key == '_uniqueid') {
              continue;
            }
            fields.push({
              name: key || '',
              type: item.type || 'string',
              length: item.length || 0,
              title: item.title || '',
              required: item.required || false,
              default: item.default || '',
              table: item.table || '',
              form: item.form || ''
            });
          }
          this.fields = this.$admin.copy(fields);
        }
      }).catch(error => {
        console.log('错误', error);
      });
    },
    handleTableList() {
      this.$cloud.tables().all({
        'AppID': this.$cloud.AppID
      }).then(res => {
        let dataMenu = [];
        for (let i in res) {
          let item = res[i];
          dataMenu[i] = {
            title: item.name,
            icon: 'h-icon-calendar',
            key: item.name
          };
        }
        this.menuData[0].children = dataMenu;
      }).catch(error => {
        console.log('错误', error);
      });
    }
  }
};

</script>
<style type="text/css">
</style>
